﻿using Newtonsoft.Json;
using SheXiangTou.Beans;
using SheXiangTou.Beans.LocalModel;
using SheXiangTou.Tools;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SheXiangTou.Services
{
    public class RedLineService
    {
        public static bool L_one = false;
        public static bool L_two = false;
        public static bool L_three = false;
        public static bool R_one = false;
        public static bool R_two = false;
        public static bool R_three = false;

        public static bool L_Weisui = false;
        public static bool R_Weisui = false;

        public static DateTime L_stateTime = DateTime.Now;
        public static DateTime R_stateTime = DateTime.Now;

        public static bool L_result_in = false;
        public static bool L_result_out = false;
        public static bool R_result_in = false;
        public static bool R_result_out = false;

        public static bool L_1 = false;
        public static bool L_3 = false;
        public static bool R_1 = false;
        public static bool R_3 = false;

        public static byte[] messageBuffer1 = new byte[1024];
        public static byte[] messageBuffer2 = new byte[1024];
        public static int bufferAll1 = 0;//表示messageBuffer实际已经存了多少接收的数据
        public static int bufferAll2 = 0;//表示messageBuffer实际已经存了多少接收的数据

        public static bool L_1_img = false;
        public static bool L_2_img = false;
        public static bool L_3_img = false;

        public static bool R_1_img = false;
        public static bool R_2_img = false;
        public static bool R_3_img = false;

        public static bool L_FACR_Red = false;//第一道红外给出状态 
        public static bool R_FACR_Red = false;//第一道红外给出状态
        public static bool L_FACR_Mac = false;//识别机器给出是否有刷脸通过行为
        public static bool R_FACR_Mac = false;//识别机器给出是否有刷脸通过行为

        public void Start()
        {
            Socket client1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            Socket client2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            IPEndPoint endpoint1 = new IPEndPoint(IPAddress.Parse(ConfigerService.RedLine_Ip1), int.Parse(ConfigerService.RedLine_Port));
            IPEndPoint endpoint2 = new IPEndPoint(IPAddress.Parse(ConfigerService.RedLine_Ip2), int.Parse(ConfigerService.RedLine_Port));

            client1.Connect(endpoint1);
            Thread thread1 = new Thread(ReciveMsg1);
            thread1.Start(client1);
            Console.WriteLine("1号红外连接成功！");

            client2.Connect(endpoint2);
            Thread thread2 = new Thread(ReciveMsg2);
            thread2.Start(client2);
            Console.WriteLine("2号红外连接成功！");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pictureName">照片URL</param>
        /// <param name="alarmTypeStr">告警内容</param>
        /// <param name="LabaSTR">喇叭内容 如6,3</param>
        static void Add_Alarm(string pictureName, string alarmTypeStr, uint alarmTyp, string LabaSTR, string CardNumS = "")
        {
            string HeadPicture = string.Empty;
            if (pictureName != null)
            {
                HeadPicture = ConfigerService.Picture_Url_Prefix + "\\" + pictureName;
                OssService.OssUpload(HeadPicture, pictureName);
                AlarmScreen alarmScreen = new AlarmScreen
                {
                    alarmType = alarmTypeStr,
                    filePath = HeadPicture.Remove(0, ConfigerService.Picture_Url_Prefix.Length)
                };
                RabbitMqService.Publish_Local_Message_Async(JsonConvert.SerializeObject(alarmScreen), ConfigerService.Direct_Screen_Exchange, ConfigerService.Alarm_Screen_Queue);//发送事件给大屏
            }

            TbRzAlarm rzAlarm = new TbRzAlarm()
            {
                AlarmType = alarmTyp,
                AlarmMessage = alarmTypeStr,
                Inout = 1,
                Mask = 0,
                Helmet = 0,
                CardType = 0,
                CreateTime = DateTime.Now,
                CardNum = CardNumS,
                HeadPicture = HeadPicture,
                OssPicture = ConfigerService.ossurlpre + ConfigerService.objectName + pictureName,
                OssUploadstate = 1,
                Uploadstate = 0
            };
            LocalDatabaseService.AddAlarm_Async(rzAlarm);
            //RabbitMQService.Publish_Message_Local(LabaSTR, Configer.Local_Laba_Exchange, Configer.Laba_Rz_Queue);
        }
        /// <summary>
        /// 接受数据
        /// </summary>
        /// <param name="o"></param>
        void ReciveMsg1(object o)
        {
            try
            {
                Socket client = o as Socket;
                byte[] ccc = new byte[10];
                while (true)
                {
                    int z = 0;//收到的数据缓存保存位置
                    while (bufferAll1 >= 10)
                    {
                        if (messageBuffer1[z] == 0x0a)
                        {
                            Buffer.BlockCopy(messageBuffer1, z, ccc, 0, 10);
                            if (Compare(ccc))
                            {
                                bufferAll1 -= 10;
                                z += 10;
                            }
                            else
                            {
                                bufferAll1 -= 1;
                                z += 1;
                            }
                        }
                        else
                        {
                            bufferAll1 -= 1;
                            z += 1;
                        }
                    }
                    Buffer.BlockCopy(messageBuffer1, z, messageBuffer1, 0, bufferAll1);
                    byte[] arrlist = new byte[1024];
                    int length = client.Receive(arrlist);
                    if (length == 0)//检查连接是否断开
                    {
                        client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                        while (true)
                        {
                            Thread.Sleep(5000);
                            try { client.Connect(new IPEndPoint(IPAddress.Parse(ConfigerService.RedLine_Ip1), int.Parse(ConfigerService.RedLine_Port))); } catch { }
                            if (client.Connected)
                                break;
                        }
                    }
                    Buffer.BlockCopy(arrlist, 0, messageBuffer1, bufferAll1, length);
                    bufferAll1 += length;
                }
            }
            catch { }
        }
        void ReciveMsg2(object o)
        {
            try
            {
                Socket client = o as Socket;
                byte[] ccc = new byte[10];
                while (true)
                {
                    int z = 0;//收到的数据缓存保存位置
                    while (bufferAll2 >= 10)
                    {
                        if (messageBuffer2[z] == 0x0a)
                        {
                            Buffer.BlockCopy(messageBuffer2, z, ccc, 0, 10);
                            if (Compare(ccc))
                            {
                                bufferAll2 -= 10;
                                z += 10;
                            }
                            else
                            {
                                bufferAll2 -= 1;
                                z += 1;
                            }
                        }
                        else
                        {
                            bufferAll2 -= 1;
                            z += 1;
                        }
                    }
                    Buffer.BlockCopy(messageBuffer2, z, messageBuffer2, 0, bufferAll2);
                    byte[] arrlist = new byte[1024];
                    int length = client.Receive(arrlist);
                    if (length == 0)//检查连接是否断开
                    {
                        client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                        while (true)
                        {
                            Thread.Sleep(5000);
                            try { client.Connect(new IPEndPoint(IPAddress.Parse(ConfigerService.RedLine_Ip2), int.Parse(ConfigerService.RedLine_Port))); } catch { }
                            if (client.Connected)
                                break;
                        }
                    }
                    Buffer.BlockCopy(arrlist, 0, messageBuffer2, bufferAll2, length);
                    bufferAll2 += length;
                }
            }
            catch { }
        }
        /// <summary>
        /// 返回0表示无匹配项 ，返回其他一依次表示匹配的指令含义
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        bool Compare(byte[] m)
        {
            if (!MathTool.CheckCRC(m)) //CRC校验
                return false;
            if (m[1] == 3)//左侧门
            {
                if (m[2] == 1)//第一道红外先触发
                {
                    L_FACR_Red = true;
                    if (!L_1 && !L_3)
                        L_1 = true;
                }
                else if (m[4] == 1)//第三道红外先触发
                {
                    if (!L_1 && !L_3)
                        L_3 = true;
                }
                if (m[3] == 1 || m[2] == 1 || m[4] == 1)
                    L_stateTime = DateTime.Now;
                if (L_1)
                {
                    if (m[2] == 1 && !L_three)
                        L_one = true;
                    if (m[3] == 1 && L_one)
                        L_two = true;
                    if (m[4] == 1 && L_two)
                        L_result_in = true;
                    if (L_result_in && m[2] == 0)
                        L_1 = false;
                    if (m[2] == 1 && !L_Weisui && m[4] == 1)
                        L_Weisui = true;
                }
                else if (L_3)
                {
                    if (m[4] == 1 && !L_one)
                        L_three = true;
                    if (m[3] == 1 && L_three)
                        L_two = true;
                    if (m[2] == 1 && L_two)
                        L_result_out = true;
                    if (L_result_out && m[4] == 0)
                        L_3 = false;
                }

                if ((DateTime.Now - L_stateTime).TotalMilliseconds > 2000)
                {
                    L_1 = false;
                    L_3 = false;
                    L_one = false;
                    L_two = false;
                    L_three = false;
                    L_result_in = false;
                    L_result_out = false;
                    L_Weisui = false;
                    L_FACR_Red = false;
                }
            }
            else//右侧门
            {
                if (m[2] == 1)//第一道红外先触发
                {
                    R_FACR_Red = true;
                    if (!R_1 && !R_3)
                        R_1 = true;
                }
                else if (m[4] == 1)//第三道红外先触发
                {
                    if (!R_1 && !R_3)
                        R_3 = true;
                }
                if (m[3] == 1 || m[2] == 1 || m[4] == 1)
                    R_stateTime = DateTime.Now;
                if (R_1)
                {
                    if (m[2] == 1 && !R_three)
                        R_one = true;
                    if (m[3] == 1 && R_one)
                        R_two = true;
                    if (m[4] == 1 && R_two)
                        R_result_in = true;
                    if (R_result_in && m[2] == 0)
                        R_1 = false;
                    if (m[4] == 1 && !R_Weisui && m[2] == 1)
                        R_Weisui = true;
                }
                else if (R_3)
                {
                    if (m[4] == 1 && !R_one)
                        R_three = true;
                    if (m[3] == 1 && R_three)
                        R_two = true;
                    if (m[2] == 1 && R_two)
                        R_result_out = true;
                    if (R_result_out && m[4] == 0)
                        R_3 = false;
                }

                if ((DateTime.Now - R_stateTime).TotalMilliseconds > 2000)
                {
                    R_1 = false;
                    R_3 = false;
                    R_one = false;
                    R_two = false;
                    R_three = false;
                    R_result_in = false;
                    R_result_out = false;
                    R_Weisui = false;
                    R_FACR_Red = false;
                }
            }
            return true;
        }
        public static void RedLineCheck(TbRzAlarm tbRzAlarm, int doorID)
        {    //doorID=1左出 2左进 3右出 4右进
            //Task.Factory.StartNew(() => //采用异步方法
            //{
            //    Console.WriteLine("=====开始判断进出:");
            //    DateTime startT = DateTime.Now;
            //    while (true)
            //    {
            //        if (doorID == 1 || doorID == 2)
            //            L_FACR_Mac = true;
            //        if (doorID == 3 || doorID == 4)
            //            R_FACR_Mac = true;
            //        #region 判断是否完全进去
            //        if (doorID == 1 && L_result_out)
            //        {
            //            Console.WriteLine("左侧正常出场");
            //            #region 判断尾随
            //            if (L_Weisui)
            //            {
            //                string pictureName = MachineControl.YuYan_GetJpeg();
            //                Add_Alarm(pictureName, "尾随警告", 49, "10,3");
            //            }
            //            L_Weisui = false;
            //            #endregion
            //            Add_InOut_EnterRecord(tbRzAlarm);
            //            if (Configer.UseShuRenTou)
            //            {
            //                string pictureName = Configer.Alarm_Prefix + "\\" + MachineControl.YuYan_GetJpeg();//拍照
            //                PeopleCountService.peopleCount.Add("L,out," + pictureName);
            //            }
            //            break;
            //        }
            //        else if (doorID == 2 && L_result_in)
            //        {
            //            Console.WriteLine("左侧正常进场");
            //            #region 判断尾随
            //            if (L_Weisui)
            //            {
            //                string pictureName = MachineControl.YuYan_GetJpeg();
            //                Add_Alarm(pictureName, "尾随警告", 49, "10,3");
            //            }
            //            L_Weisui = false;
            //            #endregion
            //            Add_InOut_EnterRecord(tbRzAlarm);
            //            if (Configer.UseShuRenTou)
            //            {
            //                string pictureName = Configer.Alarm_Prefix + "\\" + MachineControl.YuYan_GetJpeg();//拍照
            //                PeopleCountService.peopleCount.Add("L,in," + pictureName);
            //            }
            //            break;
            //        }
            //        else if (doorID == 3 && R_result_out)
            //        {
            //            Console.WriteLine("右侧正常出场");
            //            #region 判断尾随
            //            if (R_Weisui)
            //            {
            //                string pictureName = MachineControl.YuYan_GetJpeg();
            //                Add_Alarm(pictureName, "尾随警告", 49, "10,3");
            //            }
            //            R_Weisui = false;
            //            #endregion
            //            Add_InOut_EnterRecord(tbRzAlarm);
            //            if (Configer.UseShuRenTou)
            //            {
            //                string pictureName = Configer.Alarm_Prefix + "\\" + MachineControl.YuYan_GetJpeg();//拍照
            //                PeopleCountService.peopleCount.Add("R,out," + pictureName);
            //            }
            //            break;
            //        }
            //        else if (doorID == 4 && R_result_in)
            //        {
            //            Console.WriteLine("右侧正常进场");
            //            #region 判断尾随
            //            if (R_Weisui)
            //            {
            //                string pictureName = MachineControl.YuYan_GetJpeg();
            //                Add_Alarm(pictureName, "尾随警告", 49, "10,3");
            //            }
            //            R_Weisui = false;
            //            #endregion
            //            Add_InOut_EnterRecord(tbRzAlarm);
            //            if (Configer.UseShuRenTou)
            //            {
            //                string pictureName = Configer.Alarm_Prefix + "\\" + MachineControl.YuYan_GetJpeg();//拍照
            //                PeopleCountService.peopleCount.Add("R,in," + pictureName);
            //            }
            //            break;
            //        }
            //        else if (doorID == 1 && L_result_in)
            //        {
            //            Console.WriteLine("左侧非正常进场");
            //            if (Configer.UseShuRenTou)
            //            {
            //                string pictureName = Configer.Alarm_Prefix + "\\" + MachineControl.YuYan_GetJpeg();//拍照
            //                PeopleCountService.peopleCount.Add("L,in," + pictureName);
            //            }
            //            break;
            //        }
            //        else if (doorID == 2 && L_result_out)
            //        {
            //            Console.WriteLine("左侧非正常出场");
            //            if (Configer.UseShuRenTou)
            //            {
            //                string pictureName = Configer.Alarm_Prefix + "\\" + MachineControl.YuYan_GetJpeg();//拍照
            //                PeopleCountService.peopleCount.Add("L,out," + pictureName);
            //            }
            //            break;
            //        }
            //        else if (doorID == 3 && R_result_in)
            //        {
            //            Console.WriteLine("右侧非正常进场");
            //            if (Configer.UseShuRenTou)
            //            {
            //                string pictureName = Configer.Alarm_Prefix + "\\" + MachineControl.YuYan_GetJpeg();//拍照
            //                PeopleCountService.peopleCount.Add("R,in," + pictureName);
            //            }
            //            break;
            //        }
            //        else if (doorID == 4 && R_result_out)
            //        {
            //            Console.WriteLine("右侧非正常出场");
            //            if (Configer.UseShuRenTou)
            //            {
            //                string pictureName = Configer.Alarm_Prefix + "\\" + MachineControl.YuYan_GetJpeg();//拍照
            //                PeopleCountService.peopleCount.Add("R,out," + pictureName);
            //            }
            //            break;
            //        }
            //        #endregion
            //        if ((DateTime.Now - startT).TotalMilliseconds > 5500)
            //        {
            //            Console.WriteLine(DateTime.Now + "判断是否进出超时！！！");
            //            break;
            //        }
            //    }
            //    if (doorID == 2 || doorID == 1)
            //    {
            //        L_1 = false;
            //        L_3 = false;
            //        L_1_img = false;
            //        L_2_img = false;
            //        L_result_in = false;
            //        L_result_out = false;
            //    }
            //    else if (doorID == 4 || doorID == 3)
            //    {
            //        R_1 = false;
            //        R_3 = false;
            //        R_1_img = false;
            //        R_2_img = false;
            //        R_result_in = false;
            //        R_result_out = false;
            //    }
            //    if (doorID < 3)
            //        MachineControl.Device_Pass_State[0] = false;
            //    else
            //        MachineControl.Device_Pass_State[1] = false;
            //    Console.WriteLine(DateTime.Now + " =====结束进场判断-->");
            //});
        }
    }
}
